/*
 * * * Compile_AHK SETTINGS BEGIN * * *

[AHK2EXE]
Exe_File=C:\Dropbox\SVN\PM App Launcher\Include\CWI SB\CWI Settings.exe
Created_Date=1
Execution_Level=3
[VERSION]
Resource_Files=C:\Dropbox\SVN\PM App Launcher\Resource\CSB_icon.ico
Set_Version_Info=1
Company_Name=WSNH Apps
File_Description=Change display settings and calibration for CWI Search Bar
File_Version=2.0.1.3
Inc_File_Version=1
Internal_Name=CWI Settings.exe
Legal_Copyright=WSNH Apps
Original_Filename=CWI Settings.exe
Product_Name=AutoHotkey_L
Product_Version=1.1.5.3
Set_AHK_Version=1
[ICONS]
Icon_1=C:\Dropbox\SVN\PM App Launcher\Resource\CSB_icon.ico

* * * Compile_AHK SETTINGS END * * *
*/

;_____________________________________________________________________
;---------------------------------------------------------------------
;	File: CWI Settings
;---------------------------------------------------------------------
;	(see ..\..\..\Resource\CSB_ScreenShot-Settings.png)
;
;	Group: Overview
;		Settings GUI for CWI Search bar. Allows user to set the 
;		auto-hide mode, default CWI view for different objet types, 
;		re-calibrate etc. Also used to calibrate for first time setup.
;
;	Group: About
;		General script information
;
;		- *Written By:* 	Rameen Bakhtiary
;		- *Last Modified:*	11/28/2011
;---------------------------------------------------------------------
 #NoEnv
 #SingleInstance, Ignore
 SetWorkingDir %A_ScriptDir%
 CoordMode, tooltip, screen
 CoordMode, Mouse, Relative     
 SendMode, Input 
 Functions()
;_____________________________________________________________________
;---------------------------------------------------------------------





 
 
;=================================================================
;                        GLOBAL VARIABLES
;=================================================================
	USfPath = CWI User Settings.ini ;User setting file name
	SetWorkingDir % A_ScriptDir
	OnExit, checkNewbie
	CALLIBRATION_PIC	= %A_ScriptDir%\..\..\Resource\CSB_cal1.bmp





;=================================================================
;		TRAY ICON FROM COMPILED RESOURCE
;=================================================================
	if a_iscompiled
		menu, tray, icon, %a_scriptfullpath%, -159






;==================================================================
;         HOTKEY:  <Esc>  ABORTS  CALIBRATION
;==================================================================
	Hotkey, ~esc, abortCalib
	Hotkey, ~esc, Off  




            
			
;=============================================================================
;                          Get monitor coordinate info
;=============================================================================
	SysGet, numMons, MonitorCount
	SysGet, leftMon1, Monitor, 1  
	leftMon := leftMon1Right    ; Size of Left monitor
	If numMons>1     ;Detected multiple monitors (assume 2)
	{
		SysGet, totalMon, Monitor, 2    ; totalMonRight = total (combined) size of monitors
		rightMon := totalMonRight - leftMon      ;Size of Right monitor
		If rightMon < 0     ;Left And Right monitors are reverse referenced as 2 And 1
		{
			leftMon:=leftMon+rightMon
			rightMon:=rightmon*-1
		}
	}
	rightMonC := leftMon + (rightMon/2)      ;Center of Right monitor
	leftMonC := leftMon / 2        ;Center of Left monitor
	xPos := leftMonC - (guiWidth/2)      ; Gui Top left.  Centered to Left monitor    
				
				
			
			
			
			
			
;=============================================================================
;                        CHECK FOR CALLIBRATION IN REG
;=============================================================================			

	IniRead, sText_y, %A_ScriptDir%\callibrationSettings.ini, fieldCoords, ST, Error
	IniRead, fieldxpos, %A_ScriptDir%\callibrationSettings.ini, fieldCoords, x, Error
	
	if (sText_y = "Error" || fieldxpos = "Error") {
		newbie:=true
		
		;_______________________________________________________
		; 		NO CALLIBRATION INI FILE--LOOK FOR VALUES IN REG
		;
		RegRead, sText_y, HKCU, Software\CWI Search Bar\fieldCoords, ST
		If !ErrorLevel
		{
			RegRead, fieldxpos, HKCU, Software\CWI Search Bar\fieldCoords, x
			If !ErrorLevel
			{
				;___________________________________
				; 		GOT BOTH VALUES FROM THE REG
				;
				 IniWrite, %fieldxpos%, %A_ScriptDir%\callibrationSettings.ini, fieldCoords, x
				 IniWrite, %sText_y%, %A_ScriptDir%\callibrationSettings.ini, fieldCoords, ST
				 Sleep 100
				 goto userSettingsCheck
			}
		}
		
		
		;___________________________________________________________
		; 		NOT FOUND IN REG-- CHECK FOR RTA MANAGER CALLIB FILE
		;
		IfExist, %A_MyDocuments%\Halliburton RTA Manager\Include\calibrationSettings.ini					
		{	
			;__________________________________________
			; 		GOT THE VALUES FROM RTA MANAGER INI
			;
			FileCopy, %A_MyDocuments%\Halliburton RTA Manager\Include\calibrationSettings.ini, %A_ScriptDir%\callibrationSettings.ini,1
			Sleep 100
			goto userSettingsCheck
		}
		
		;_____________________________
		; 	OTHERWISE, RUN CALIBRATION
		;
		Gosub, createSetupFile   
		Gosub, settingshelp			
	}





;=================================================================
;            CHECK FOR USER SETTINGS INI AND SET GUI VALUES
;=================================================================
userSettingsCheck:

	;________________________________________
	; 	USERSETTINGS INI FILE DOESN'T EXIST
	;
	IfNotExist, %A_ScriptDir%\CWI User Settings.ini
	{
		enableOpts=venableAH
		instantOpts=vinstant
		delayOpts=vtimeDelay
		timeOpts=vtimed
	}
	
	;___________________________
	; 	SETTINGS FILE DOES EXIST
	;
	Else{		

		IniRead, tabbed, CWI User Settings.ini, CWIsettings, tabBrowsing, 
		IniRead, timeDelay, CWI User Settings.ini, CWIsettings, hideWaitTime,
		IniRead, showOnRight, CWI User Settings.ini, CWIsettings, rightMon,
		IniRead, showOnBottom, CWI User Settings.ini, CWIsettings, monBottom,
		IniRead, custView_RTA, CWI User Settings.ini, CWIsettings, custView_RTA, "m"
		IniRead, custView_Task, CWI User Settings.ini, CWIsettings, custView_Task, "sig"
		IniRead, custView_Part, CWI User Settings.ini, CWIsettings, custView_Part, ""
	}





;=================================================================
;         SET GUI CONTROLS TO REFLECT USER'S CURRENT SETTINGS
;=================================================================
	rmonopts := (showOnRight ? "+Checked " : "") "vShowOnRightMon"	 ;--SHOW ON RIGHT
	bmonopts := (showOnBottom ? "+Checked " : "") "vShowOnMonBottom"	;--SHOW ON BOTTOM
	tabOpts := (tabbed ? "+Checked " : "") "vtabbed"	;--TABBED BROWSING
	;--AUTO-HIDE SETTINGS
	If (timeDelay = 0){  		;--INSTANT HIDE
		enableOpts=+Checked venableAH
		instantOpts=+Checked vinstant
		delayOpts=vtimeDelay
		timeOpts=vtimed
	}else if (timeDelay = -1){	;--NO HIDE
		enableOpts=venableAH
		instantOpts=vinstant
		delayOpts=vtimeDelay
		timeOpts=vtimed
	}Else{						;--TIMED HIDE		
		delayOpts := (timeDelay = 1 ? "Choose1" 
			:timeDelay = 2 ? "Choose2"
			:timeDelay = 5 ? "Choose3"
			:timeDelay = 10 ? "Choose4"				 
			: "") "vtimeDelay"
		enableOpts=+Checked venableAH
		instantOpts=vinstant
		timeOpts=+Checked vtimed
	}	







;=================================================================
;											BUILD GUI
;=================================================================
	;Tabbed browsing Checkbox
	Gui, Add, Checkbox, x15 y5 w110 h20 %tabOpts%, Tabbed Browsing

	;Auto-Hide GroupBox
	Gui, Add, GroupBox, x15 y72 w260 h80 section, Auto-Hide Setting

	;Right monitor Checkbox
	Gui, Add, Checkbox, x15 y25 h20 %rmonopts%, Right Mon.


	;Enable auto-Hide Checkbox
	Gui, Add, Checkbox, x15 y50 w120 h20 %enableOpts%, Enable Auto-Hide

	;Time delay Radio
	Gui, Add, Radio, x25 y92 w130 h20 %timeOpts%, Time delay [seconds]:
	;Instant Hide Radio
	Gui, Add, Radio, x25 y112 w90 h30 %instantOpts%, Instant Hide
	;Time delay dropdown
	Gui, Add, DropDownList, x155 y92 w100 h21 +AltSubmit +r4 %delayOpts%, 1 Second|2 Seconds|5 Seconds|10 Seconds

	;Submit Button
	Gui, Add, Button, x65 y166 w70 h20 +Default gsettingsSubmit, Submit
	;Right monitor Checkbox
	Gui, Add, Checkbox, x90 y25 h20 %bmonopts%, Mon. Bottom
	;Help Button
	Gui, Add, Button, x145 y166 w70 h20 gsettingshelp, Help

	;Part default view settings
	;~ gui, add, GroupBox, 

	;Re-calibrate Button
	Gui, Add, Button, x181 y10 w85 h23 gRecalibrate, Re-Calibrate

	;Gui Show
	Gui, Show, w291 h199, CWI User Settings


	 ;_______________________________________________________
	 ; 	START TIMER FOR HANDLING GUI DISABLE/ENABLE CONTROLS
	 ;
	 SetTimer, theDisabler, 200
	Return





;____________________________________ E N D   A U T O - R U N ______________________________________
;%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%&%







;===================================================
;							Submit settings BUTTON
;===================================================
settingsSubmit:
	Gui, Submit
	Gui, Destroy
	;|  If showonrightmon
		;|  showonright:=1
	;|  If !showonrightmon
		;|  showonright:=0
	;|  If showonmonbottom
		;|  showonbottom:=1
	;|  If !showonmonbottom
		;|  showonbottom:=0
	checkFreq:=250
	If tabbed
		tabVal:=1
	If !tabbed
		tabVal:=0
	If !enableAH
		waitTime:=-1
	If (instant){
		waitTime:=0
		checkFreq:=150
	}
	If (timed){
		If timeDelay = 1
			waitTime=1
		If timeDelay = 2
			waitTime=2
		If timeDelay = 3
			waitTime=5
		If timeDelay = 4
			waitTime=10
	}
	IniWrite, %WaitTime%, CWI User Settings.ini, CWIsettings, hideWaitTime
	IniWrite, %checkFreq%, CWI User Settings.ini, CWIsettings, checkFreq
	IniWrite, %tabVal%, CWI User Settings.ini, CWIsettings, tabBrowsing
	IniWrite, %showonRIGHTmon%, CWI User Settings.ini, CWIsettings, rightMon
	IniWrite, %showonMonBOTTOM%, CWI User Settings.ini, CWIsettings, monBottom
	Goto GuiClose
Return






;===================================================
;	Enable / Disable controls on GUI
;===================================================
theDisabler:
	Gui, Submit, NoHide
	If !(enableAH){
		GuiControl,Disable,button5
		GuiControl,Disable,button6
		GuiControl,,button5,0
		GuiControl,,button6,0
	}
	If (enableAH){
		If !timed And !instant
			GuiControl,Disable,button7
		GuiControl,Enable,button5
		GuiControl,Enable,button6
	}
	If !timed
		GuiControl,Disable,ComboBox1
	If (timed){
		GuiControl,Enable,ComboBox1	
		If !timedelay
			GuiControl,Disable,button7
		If timeDelay
			GuiControl,Enable,button7
	}
	If instant
		GuiControl,Enable,button7
Return





;===================================================
;				Re-Calibrate BUTTON
;===================================================
Recalibrate:
	MsgBox, 36, Are you sure?, Begin CWI calibration?
	IfMsgBox, Yes
	{	Gui, Destroy
		Gosub, createSetupFile
		Sleep, 250
		Reload
	}
Return







;__________________________________________________________________________________
;##################################################################################
;
;	                                  C A L I B R A T I O N
;__________________________________________________________________________________
;##################################################################################
createSetupFile:
	       			
	
	;Open CWI window
	;=================
	run, iexplore.exe http://cwiprod.corp.halliburton.com/cwi/AdvLookup.jsp
	
	WinActivate, Advanced Lookup -
	WinWaitActive, Advanced Lookup -
	IfWinNotActive, Advanced Lookup -
		WinActivate, Advanced Lookup -
	Sleep, 400
	StatusBarWait,Done,,1,Advanced Lookup -
	Sleep 200
	StatusBarWait,Done,,1,Advanced Lookup -
	Sleep 100
	StatusBarWait,Done,,1,Advanced Lookup -
	Sleep 100
	StatusBarWait,Done,,1,Advanced Lookup -
	Sleep 150
	
	Hotkey, ~esc, On    ;Activate Esc Hotkey to Abort calibration
	

	;Show help image at top-center of screen w/CWI window
	;==============================================
	WinGetPos, calibWinXpos, calibWinYpos,,, Advanced Lookup -
	leftMon75percent := (leftMon*.75)
	IfLess, calibWinXpos, %leftMon75percent%     ;Adv. Lookup window opened In Left monitor
		calibSplashX := leftMonC - (445/2)
	IfGreater, calibWinXpos, %leftMon75percent%      ;Adv. Lookup opened In Right monitor
		calibSplashX := rightMonC - (445/2)
	SplashImage, %CALLIBRATION_PIC%, w460 h165 B1 x%calibSplashX% y0, , ,		;Show image
	
	
	;Wait for and record click
	;=====================
	tryAgain1:
	WinActivate, Advanced Lookup -
	Sleep, 100
	KeyWait, LButton, d		;Wait for left-click
	MouseGetPos, sText_x, sText_y, winClickedIn 	;Get coords & window of click
	WinGetTitle, clickedInTitle, Ahk_ID %winClickedIn%
	if ! instr(clickedInTitle, "Advanced Lookup -"){  	   ;Clicked outside of CWI window
		MsgBox, 48, OOPS!, `nYou didn't seem to Click within the CWI window...`n`nTry again.`n`n`n
		Goto, tryAgain1
	}		
	SplashImage, Off		;Remove Image		
	Hotkey, ~esc, Off       ;Disable aborting calibration hotkey
	
	
	;_____________________________________________
	; 	WRITE CALIBRATION VALUES TO INI / REGISTRY
	;
	;~ RegWrite, REG_SZ, HKCU, Software\CWI Search Bar\fieldCoords, x, %sText_x%
	;~ RegWrite, REG_SZ, HKCU, Software\CWI Search Bar\fieldCoords, ST, %sText_y%
	IniWrite, %sText_x%, %A_ScriptDir%\callibrationSettings.ini, fieldCoords, x
	IniWrite, %sText_y%, %A_ScriptDir%\callibrationSettings.ini, fieldCoords, ST
	
	
	
	;Close CWI
	;===========
	WinClose, Advanced Lookup -
	Sleep 150		
	MsgBox, 64, , Calibration Successful. Settings have been saved.
Return






;===================================================
;									Help Button
;===================================================
settingshelp:
	;**  MsgBox, 64, CWI Search Bar Settings..., `n		CWI Search Bar Settings Help...`n`n-If your browser uses Tabbed browsing`, Check the "tabbed browsing" box.`n (Tabbed browsing means that when you perform a search Or Click a link the`n  result Is opened In a new Tab within the same window.`n  **If you are having a problem where your search window Is closing before you see any results`,`n      Check this box.**)`n`n-Enable Auto-Hide to make the search bar collapse after a Set amount of time.`n The search bar will re-appear when you hover your Mouse over the collapsed bar`n`n-Click the "Help" Button to re-open this screen.`n`n
Return







;===================================================
;			Abort Calibration : <Esc> hotkey
;===================================================
abortCalib:
    MsgBox, 308, Abort Calibration, `nAre you sure you want to Abort calibration?`n`n
    IfMsgBox, Yes    ; Abort calibration
    {
        If newbie   ; Exit App If First Time user/no INI file found
        {
            SplashImage, Off
            Sleep, 200
            MsgBox, 0, Goodbye..., `nYou must create a calibration file In order to use the CWI Search Bar.`n`nThe program will now exit.`n
            WinClose, Advanced Lookup -
            ExitApp
        }
        WinClose, Advanced Lookup -
        Reload      ; Close CWI window And Reload script
    }        
Return





;===================================================
;		If closed w/o creating calib file: exit
;===================================================
checkNewbie:
	IfNotExist, CWI User Settings.ini
		MsgBox, 0, Goodbye..., `nYou must create a calibration file In order to use the CWI Search Bar.`n`nThe program will now exit.`n
	ExitApp
Return


GuiClose:
ExitApp